/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-08-04 11:53:46
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-08-07 20:54:37
 * @FilePath: /code/lesson25/test1/task.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>

typedef void(*work_t)(int);
typedef void(*task_t)(pid_t, int);

void PrintLog(pid_t subprocess_id, int rfd)
{
   std::cout << "subprocess_id: " << subprocess_id << " rfd is: " << rfd << " task is PrintLog\n" << std::endl;
}

void ReloadConf(pid_t subprocess_id, int rfd)
{
    std::cout << "subprocess_id: " << subprocess_id << " rfd is: " << rfd << " task is ReloadConf\n" << std::endl;
}

void ConnectMysql(pid_t subprocess_id, int rfd)
{
    std::cout << "subprocess_id: " << subprocess_id << " rfd is: " << rfd << " task is ConnectMysql\n" << std::endl;
}

task_t task[3] = {PrintLog, ReloadConf, ConnectMysql};

//size_t int
int NextTask()
{
    return rand() % 3;//C语言stdlib中的rand
}

void worker(int rfd)
{
    while(true)
    {
        size_t commandcode;//命令码一定大于0

        //写端没有关闭，管道内没有数据，阻塞等待
        size_t n = read(0, &commandcode, sizeof(commandcode));//一次读取一个任务码大小

        //cout << fflush;立即刷新
        //std::cout << "commandcode is: " << commandcode << " rfd is: " << rfd << std::endl;

        //if(n > 0) err
        if(n == sizeof(commandcode))//先判断是否读取到，之后再判断任务码的合法性
        {
            if(commandcode >= 3) continue;//如果任务码大于等于3，则任务码不合法
            task[commandcode](getpid(), rfd);
        }
        else if(n == 0)
            break;

        //sleep(1);
    }
}